package com.atguigu.service;

import com.atguigu.bean.Menu;
import com.atguigu.bean.Role;
import com.atguigu.bean.UserInfo;
import com.atguigu.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author mqx
 * @date 2020 年 7 月 20 日 0020 14:37:20
 */
@Service
public class UsersServiceImpl implements UserDetailsService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("走了登录！");
        UserInfo users = userInfoMapper.selectByUserName(username);
        // 判断用户对象是否为空
        if (null==users){
            System.out.println("用户不存在！");
            throw  new UsernameNotFoundException("用户名不存在！");
        }
        // 获取到用户角色，菜单列表
        List<Role> roleList = userInfoMapper.selectRoleByUserId(users.getId());
        List<Menu> menuList = userInfoMapper.selectMenuByUserId(users.getId());

        // 声明一个集合List<GrantedAuthority>
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        // 处理角色
        for (Role role : roleList) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority("ROLE_"+role.getName());
            grantedAuthorityList.add(simpleGrantedAuthority);
        }
        // 处理权限
        for (Menu menu : menuList) {
            grantedAuthorityList.add(new SimpleGrantedAuthority(menu.getPermission()));
        }
        // 将用户角色，权限添加到当前用户
        return new User(username,users.getPassword(),grantedAuthorityList);
    }
}
